﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Manager
/// </summary>
public class Manager
{

    public static List<FoodValue> GetAll()
    {
        FoodValueFacade facade = new FoodValueFacade();
        return facade.GetAllValues();
    }

    static public FoodValue GetFoodValue(int foodcode)
    {
        FoodValueFacade facade = new FoodValueFacade();
        return facade.GetFoodValue(foodcode);
    }

    private const string SELECTION_MODEL_KEY = "foolvalueselection";
    
    public static SelectionModel GetSelectionModel()
    {
        SelectionModel model = null;
        try
        {
            model = HttpContext.Current.Session[SELECTION_MODEL_KEY] as SelectionModel;
        }
        catch {}
        if ( model==null)
        {
            model  = new SelectionModel ();
            model.SelectedItems = new List<SelectionItem>();
            HttpContext.Current.Session[SELECTION_MODEL_KEY] = model;
        }
        return model;
    }

    public static void SetSelectionModel(SelectionModel model)
    {
        HttpContext.Current.Session[SELECTION_MODEL_KEY] = model;
    }

    public static void AddToSelectionModel(SelectionModel model)
    {
        SelectionModel current = GetSelectionModel();
        
        Dictionary<int, double> dicModel = new Dictionary<int, double>();
        foreach (SelectionItem si in current.SelectedItems)
        {
            dicModel[si.FoodCode] = si.Amount;
        }

        foreach (SelectionItem si in model.SelectedItems)
        {
            double val = 0;
            if (dicModel.ContainsKey(si.FoodCode))
            {
                val = dicModel[si.FoodCode];
            }
            val += si.Amount;
            dicModel[si.FoodCode] = val;
        }

        SelectionModel newModel = new SelectionModel();
        foreach (int foodCode in dicModel.Keys)
        {
            newModel.SelectedItems.Add(new SelectionItem(){FoodCode = foodCode, Amount = dicModel[foodCode]});
        }

        SetSelectionModel(newModel);
    }

}